package com.study.recorderbutton.manager;

import java.io.IOException;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;

/**
 * 媒体播放工具类
 * @author Administrator
 *
 */
public class MediaManager {
	private static MediaPlayer mMediaPlayer;
	//记录是否暂停
	private static boolean isPause;
	
	/**
	 * 播放声音
	 * @param filePath
	 * @param onCompletionListener
	 */
	public static void playSound(String filePath, OnCompletionListener onCompletionListener){
		if(mMediaPlayer == null){
			mMediaPlayer = new MediaPlayer();
			
			mMediaPlayer.setOnErrorListener(new OnErrorListener() {
				
				@Override
				public boolean onError(MediaPlayer mp, int what, int extra) {
					mMediaPlayer.reset();
					return false;
				}
			});
		}else{
			mMediaPlayer.reset();
		}
		
		try {
			mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mMediaPlayer.setOnCompletionListener(onCompletionListener);
			mMediaPlayer.setDataSource(filePath);
			mMediaPlayer.prepare();
			mMediaPlayer.start();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 暂停播放
	 */
	public static void pause(){
		if(mMediaPlayer != null && mMediaPlayer.isPlaying()){
			mMediaPlayer.pause();
			isPause = true;
		}
	}
	
	/**
	 * 继续播放
	 */
	public static void resume(){
		if(mMediaPlayer != null && isPause){
			mMediaPlayer.start();
			isPause = false;
		}
	}
	
	/**
	 * 释放资源
	 */
	public static void release(){
		if(mMediaPlayer != null){
			mMediaPlayer.release();
			mMediaPlayer = null;
		}
	}

}
